#include "datapostback.h"
#include "mylogger.h"
#include "machineutil.h"
#include <QDebug>

using namespace ns_yht;

Q_GLOBAL_STATIC(DataPostback, m_instance)

namespace
{
    const QString SERVER = "iotdevice.ehanghai.cn" /* "47.98.199.227"*/;
    const QString SERVER_DEVELOP = "192.168.18.126";
    const int PORT = 9988;
}
DataPostback::DataPostback()
{
}

DataPostback::~DataPostback()
{
    delete m_tcpSocket;
}

DataPostback *DataPostback::instance()
{
    return m_instance();
}

QString DataPostback::getServer() const
{
    if (MyLogger::developDebug)
        return SERVER_DEVELOP;
    return SERVER;
}

void DataPostback::moveToThreadEx(QThread *thread)
{
    moveToThread(thread);
    m_tcpSocket = new QTcpSocket;
    m_tcpSocket->moveToThread(thread);
    connect(m_tcpSocket, &QTcpSocket::connected, this, &DataPostback::onConnected);
    connect(m_tcpSocket, &QTcpSocket::disconnected, this, &DataPostback::onDisconnected);
    connect(m_tcpSocket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::errorOccurred),
            this, &DataPostback::onError);
}

void DataPostback::onNetworkStatusChanged(bool state)
{
    if (state)
        openSocket();
    else
        closeSocket();
}

void DataPostback::openSocket()
{
    if (!m_postBack || m_tcpSocket->state() == QAbstractSocket::ConnectingState || m_tcpSocket->state() == QAbstractSocket::ConnectedState)
        return;
    closeSocket();
    m_tcpSocket->connectToHost(getServer(), PORT, QIODevice::ReadWrite, QAbstractSocket::IPv4Protocol);

#if 0
    if (m_tcpSocket->waitForConnected(3000))
    {
        if (GLOG)
            GLOG->debug("data postback tcp connectToHost succeed! ");
    }
    else
    {
        if (GLOG)
            GLOG->debug("tcp connectToHost failed! ");
    }
#endif
}

void DataPostback::onConnected()
{
    if (GLOG)
        GLOG->debug("data postback tcp connectToHost succeed! {}", getServer().toStdString());
}

void DataPostback::onDisconnected()
{
    if (GLOG)
        GLOG->debug("data postback tcp disconnected! {}", getServer().toStdString());
}

void DataPostback::onError(QAbstractSocket::SocketError socketError)
{
    if (GLOG)
        GLOG->debug("tcp connectToHost failed:{}, {}!", getServer().toStdString(), socketError);
}

void DataPostback::closeSocket()
{
    if (m_tcpSocket->isOpen())
        m_tcpSocket->close();
}

void DataPostback::sendBack(const QByteArray &msg)
{
    if (!m_postBack)
        return;
    // if (MyLogger::developDebug)
    // {
    //     MyLogger::developInfo(QString("TcpSocket state: %1").arg(m_tcpSocket->state()).toStdString());
    // }

    if ((m_tcpSocket->state() == QAbstractSocket::ConnectedState))
    {
        QByteArray data = "BlackTCP[" + MachineUtil::machineCode().toUtf8() + "]-" + msg + "\n";
        // int ret =
        m_tcpSocket->write(data);
        // if (MyLogger::developDebug)
        // MyLogger::developInfo((QString("Data Postback : %1 ").arg(ret) + msg).toStdString());
    }
    else
    {
        // MyLogger::developInfo("Data Postback : TcpSocket disconnected.");
    }
}

void DataPostback::setPostBack(bool postBack)
{
    m_postBack = postBack;
}

// bool DataPostback::getPostBack() const
// {
//     return m_postBack;
// }
